package top.lingkang.finalgateway.utils;

import cn.hutool.core.util.StrUtil;
import okhttp3.FormBody;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author lingkang
 * Created by 2024/4/27
 */
public class CommonUtils {
    public static final Field FormBody_names;
    public static final Field FormBody_values;

    static {
        try {
            FormBody_names = FormBody.Builder.class.getDeclaredField("names");
            FormBody_names.setAccessible(true);

            FormBody_values = FormBody.Builder.class.getDeclaredField("values");
            FormBody_values.setAccessible(true);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static boolean isLinux() {
        String os = System.getProperty("os.name");
        return os != null && os.toLowerCase().contains("linux");
    }

    public static boolean portIsUse(int port) {
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            // 如果能够绑定到端口，则端口未被占用
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            // 如果不能绑定到端口，则端口已被占用
            return true;
        }
    }

    public static String getUrlPath(String url) {
        try {
            URL u = new URL(url);
            return u.getPath();
        } catch (MalformedURLException e) {
            throw new RuntimeException("无法从URL中提取请求路径: " + url, e);
        }
    }

    public static URL getURL(String url) {
        try {
            return new URL(url);
        } catch (MalformedURLException e) {
            throw new RuntimeException("无法从字符串转化为URL: " + url, e);
        }
    }

    /**
     * ws://
     * wss://
     */
    public static String getWsHost(String ws) {
        if (ws.startsWith("ws")) {
            int i = ws.indexOf("/", 5);
            if (i == -1)
                return ws.substring(5);
            return ws.substring(5, i);
        } else {
            int i = ws.indexOf("/", 6);
            if (i == -1)
                return ws.substring(6);
            return ws.substring(6, i);
        }
    }

    public static String removeSpace(String str) {
        while (str.contains(" "))
            str = str.replace(" ", "");
        return str;
    }

    /**
     * /pay  /api     --> /pay/api
     * /api  /api/get --> /get
     */
    public static String getPathWithinPattern(String source, String url) {
        if (url.startsWith(source)) {
            if (url.length() == source.length())
                return "/";
            else
                return url.substring(source.length());
        }
        return source + url;
    }

    public static boolean checkIpList(String ipList) {
        while (ipList.contains(" "))
            ipList = ipList.replace(" ", "");
        return Pattern.matches("^[0-9\\n.*,]+$", ipList);
    }

    public static List<String> toIpList(String ipList) {
        List<String> list = new ArrayList<>();
        if (StrUtil.isEmpty(ipList))
            return list;
        while (ipList.contains(" "))
            ipList = ipList.replace(" ", "");
        ipList = ipList.replace("\n", ",");
        ipList = ipList.replace("\r\n", ",");
        for (String ip : ipList.split(","))
            if (ip.length() > 6)
                list.add(ip);
        return list;
    }


    // 终端

    public static boolean isWindow() {
        return System.getProperty("os.name").toLowerCase().contains("win");
    }

    public static boolean isUbuntu() {
        return getOSName().equalsIgnoreCase("ubuntu");
    }

    public static boolean isCentOS() {
        String name = getOSName();
        if (name == null)
            return false;
        return name.toLowerCase().contains("centos");
    }

    private static String osName = null;

    private static String getOSName() {
        if (osName != null)
            return osName;
        try (BufferedReader br = new BufferedReader(new FileReader("/etc/os-release"))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.startsWith("NAME=")) {
                    osName = line.substring(line.indexOf("=") + 1).replaceAll("\"", "");
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        return osName.trim();
    }

    private static String pid;

    public static String getPid() {
        if (pid != null)
            return pid;
        RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        pid = runtimeMXBean.getName().split("@")[0];
        return pid;
    }
}
